package com.kongshidian.ui.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.annotation.view.ViewInject;

import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.adapter.MainProductRecommendAdapter;
import com.kongshidian.bean.BrandRecommend;
import com.kongshidian.bean.MainTopAdvertisement;
import com.kongshidian.bean.PageEntity;
import com.kongshidian.bean.Product;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.BrandListActivity;
import com.kongshidian.ui.MainActivity;
import com.kongshidian.ui.ProductDetailActivity;
import com.kongshidian.ui.view.AbsScrollGridView;
import com.kongshidian.ui.view.CountdownClock;
import com.kongshidian.ui.view.MyPagerGalleryView;
import com.kongshidian.ui.view.ScrollViewRefreshProxy;
import com.kongshidian.ui.view.CountdownClock.ClockListener;
import com.kongshidian.ui.view.MyPagerGalleryView.MyOnItemClickListener;
import com.kongshidian.ui.view.ScrollViewRefreshProxy.OnRefreshActionListener;
import com.kongshidian.util.NetworkUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;



/***
 * 顶级空时店
 * @author ghg
 *
 */
@SuppressLint("HandlerLeak")
public class CopyOfTopKSDFragment extends BaseFragment implements OnRefreshActionListener{
	
	/** 顶部branner 滚动广告 */
	LinearLayout mMainPageLin,mTimeLimitLin,mBrandGroupLin; //滚动garllery
	MyPagerGalleryView mMainPageGalleryView; //滚动garllery
	LinearLayout mMainPageGalleryLin; //底部圆点容器

	ScrollView mScrollView;
	/** 限时特卖的三张图片 */
	ImageView mTimeLimitImg1; 
	ImageView mTimeLimitImg2; 
	ImageView mTimeLimitImg3; 
	/** 团购三张图片 */
	ImageView mGroupImg1; 
	ImageView mGroupImg2; 
	ImageView mGroupImg3; 
	/**  */
	AbsScrollGridView mBrandGridView;
	AbsScrollGridView mProductRecommendGrid;
	/** 9个品牌推荐viewpage */
	ViewPager mViewPage;
	
	LinearLayout mOvalLayout; // 圆点容器 
	
	LinearLayout mMainViewpageLin; //viewpage的父layout
	
	private MainTopAdvertisement mTopAdvertisement;
	private List<MainTopAdvertisement.AdServing> mAdServings;
	private PageEntity<Product> msEntity;
	private List<Product> mSpecialSales ;
	private List<BrandRecommend> mBrandRecommends;
	private List<Product> mRecommend;
	private List<Product> mGroupRecommend;
	//	private MainBrandGridAdapter mBrandRecommendAdapter;
	//猜你喜欢
	private MainProductRecommendAdapter mProductRecommendAdapter;
	private static final String TAG = "TopKSDFragment"; 

	/** 9个品牌推荐的view视图 */
	private View view;
	private List<View> viewList;// view数组
	private int curIndex = 0;
	private int oldIndex = 0;

	PullToRefreshScrollView mPtrScrollView;
	ScrollViewRefreshProxy mScrollViewRefreshProxy;
	
	private Handler mHandler = new MyHandler(this);
	
	@Override  
	public View onCreateView(LayoutInflater inflater, ViewGroup container,  
			Bundle savedInstanceState) { 
		return inflater.inflate(R.layout.fragement_topksd, container, false);  
	}  
	
	
	
	/**
	 * 创建以后做的事情
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		//限时特卖
		mTimeLimitLin	 = (LinearLayout) getView().findViewById(R.id.time_limit_lin);
		//品牌团购
		mBrandGroupLin =  (LinearLayout) getView().findViewById(R.id.brand_group_lin);
		
		
		/** 顶部branner 滚动广告 ,商家信息*/
		mMainPageLin	 = (LinearLayout) getView().findViewById(R.id.main_branner_lin);
		mMainPageGalleryView = 		(MyPagerGalleryView) getView().findViewById(R.id.main_branner_grally);
		mMainPageGalleryLin =		(LinearLayout) getView().findViewById(R.id.main_branner_butttom_lin);
		
		 //mScrollView  = (ScrollView) getView().findViewById(R.id.topksd_scroll);
		/** 限时特卖的三张图片 */
		 mTimeLimitImg1 = (ImageView) getView().findViewById(R.id.time_limit_image1);
		 mTimeLimitImg2 = (ImageView) getView().findViewById(R.id.time_limit_image2);
		 mTimeLimitImg3 = (ImageView) getView().findViewById(R.id.time_limit_image3);
		 
		 
		/** 团购三张图片 */
		mGroupImg1 = (ImageView) getView().findViewById(R.id.main_group_img1);
		mGroupImg2 = (ImageView) getView().findViewById(R.id.main_group_img2);
		mGroupImg3 = (ImageView) getView().findViewById(R.id.main_group_img3);
		
		
		/**  */
		 mBrandGridView=	(AbsScrollGridView) getView().findViewById(R.id.main_brand_gridView);
		 mProductRecommendGrid= 	(AbsScrollGridView)getView().findViewById(R.id.main_product_recommend_grid);
		
		/** 9个品牌推荐viewpage */
		 mViewPage = (ViewPager) getView().findViewById(R.id.main_brand_recommend_viewpager);
		 mOvalLayout =  (LinearLayout) getView().findViewById(R.id.ovalLayout1);
		 mMainViewpageLin =  (LinearLayout) getView().findViewById(R.id.main_brand_viewpageLin);
		 
			mPtrScrollView = (PullToRefreshScrollView) getView().findViewById(R.id.topksd_scroll);
		 
		 init();
		
	}

	


	private void init() {

		
		// TODO Auto-generated method stub

		mScrollViewRefreshProxy = new ScrollViewRefreshProxy(mPtrScrollView);
		mScrollViewRefreshProxy.setOnRefreshActionListener(this);
		
		//将猜你喜欢改成下拉形式 ------------------------------------
		mProductRecommendAdapter = new MainProductRecommendAdapter(getActivity(), R.layout.item_main_product_recommend);
		mProductRecommendGrid.setAdapter(mProductRecommendAdapter);

		mProductRecommendGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView,
					View view, int position, long id) {
				Intent intent = new Intent(getActivity(),ProductDetailActivity.class);
				intent.putExtra("productID", mProductRecommendAdapter.getData().get(position).getId()+"");
				startActivity(intent);
			}

		});

		mScrollViewRefreshProxy.refreshing();

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		InitData();
	}
	
	
	
	private void InitData() {
		if (!NetworkUtil.isNetworkConnected(getActivity())) {							// 判断是否联网

			App.showShortToast("当前未检测到网络链接");
			mScrollViewRefreshProxy.loadRefreshActionComplete();
			return;
		}
		
//		/** 获取广告 */
//		getAdvertisementsAsync(); 
//		/** 获取特卖 */
//		getSpecialSaleSync();  
//		/** 品牌团购 */
//		getGrouponsRecommendAysnc();
		/** 获取9个品牌推荐 */
		getBrandRecommendAsync();
//		/** 猜你喜欢 */
//		getRecommendAsync();  

		
	}
	
	
	
	//Load Data Async .................................................
	/** 获取广告 */
	private void getAdvertisementsAsync() {
		new Thread(){
			public void run() {
				try {
					//获取首页头部广告
					mTopAdvertisement = WebClient.getInstance(getActivity()).adVertisement();
					mAdServings = mTopAdvertisement.getActiveServings();
					mHandler.sendEmptyMessage(0);
				} catch (Exception e) {
					mAdServings = new ArrayList<MainTopAdvertisement.AdServing>();
					mHandler.sendEmptyMessage(0);
					Log.w(TAG, "Get advertisement fail," + e.toString());
				}
			};
		}.start();
	}
	
	
	
	/** 获取特卖 */
	private void getSpecialSaleSync() {
		new Thread(){
			public void run() {
				try {
					msEntity = WebClient.getInstance(getActivity()).active("active", 1, 3, "endTime", "asc");
					mSpecialSales = msEntity.getContent();

				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
						mSpecialSales = null;
					}

				}catch (Exception e) {
					App.showLog("Get special sale," + e.toString());
				} 
				mHandler.sendEmptyMessage(1);
			};
		}.start();
	}

	
	
	/**获取9个品牌 */
	private void getBrandRecommendAsync() {
		new Thread(){
			public void run() {
				try {
					mBrandRecommends = WebClient.getInstance(getActivity()).getBrandRecommend(9);
					mHandler.sendEmptyMessage(3);
				} catch (WebException e) {
					Log.w(TAG, "Get Brand Recommend fail," + e.toString());
				}catch (Exception e) {
					Log.w(TAG, "Get Brand Recommend fail," + e.toString());
				}
			};
		}.start();
	}
	
	

	/** 获取品牌团购推荐 */
	private void getGrouponsRecommendAysnc() {
		new Thread(){
			public void run() {
				try {
					mGroupRecommend = WebClient.getInstance(getActivity()).getGrouponsRecommend(3);
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
						mGroupRecommend = null;
					}else {
						e.printStackTrace();
						App.showLog("Get Recommand fail=="+e.toString());
					}
				}catch (Exception e) {
				}
				mHandler.sendEmptyMessage(5);
			};
		}.start();

	}
	
	
	
	/** 首页单品推荐  */
	private void getRecommendAsync() {
		new Thread(){
			public void run() {
				try {
					PageEntity<Product> entry = WebClient.getInstance(getActivity()).getRecommend(1);

					mRecommend = entry.getContent();

					mHandler.sendEmptyMessage(4);
				} catch (WebException e) {
					App.showLog("Get Recommand fail=="+e.toString());
				}catch (Exception e) {
					App.showLog("Get Recommand fail=="+e.toString());
					App.showShortToast("未知错误");					
				}
			};
		}.start();


	}
	
	//Load Data Async End.................................................
		
		
		
		/**
		 * Handle下载
		 * @author ghg
		 *
		 */
		private  class MyHandler extends Handler{


			private final WeakReference<Fragment> mActivity; // activity弱引用

			public MyHandler(CopyOfTopKSDFragment topKSDFragment) {  
				mActivity = new WeakReference<Fragment>(topKSDFragment);  
			}  

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				if( mActivity.get() != null ){ //activity若已销毁。不做任何处理
					switch (msg.what) {
					case 0:
						//获取广告
						initBranner();
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;

					case 1:
						//获取特卖 
						setTimeLimitDate();				
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;

					case 3:
						//9个品牌推荐viewpage
						initViewpage();
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;
					case 4:
						//猜你喜欢
						mProductRecommendAdapter.update(mRecommend);
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;
					case 5:
						//品牌团购推荐
						if(mGroupRecommend == null || mGroupRecommend.isEmpty()){
							mBrandGroupLin.setVisibility(View.GONE);
						}else{

							ImageView[] groupImgs = new ImageView[3];
							groupImgs[0] = mGroupImg1;
							groupImgs[1] = mGroupImg2;
							groupImgs[2] = mGroupImg3;

							for (int i = 0; i < mGroupRecommend.size(); i++) {
								ImageLoader.getInstance().displayImage(mGroupRecommend.get(i).getImage(), groupImgs[i]);
							}	
							mBrandGroupLin.setVisibility(View.VISIBLE);
						}
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;

					default:
						break;
					}
				}
			}
			
		
		}
		
		/** 初始化顶部branner滚动视图 */
		private void initBranner() {
			//判空。。
			if(mAdServings == null || mAdServings.size() == 0 ){
				mMainPageLin.setVisibility(View.GONE);
				return;
			}

			String[] urlImageList  = new String[mAdServings.size()];
			for (int i = 0; i < mAdServings.size(); i++) {
				urlImageList[i] = mAdServings.get(i).getAdMaterial().getPath();
			}	     

				mMainPageGalleryView.start(getActivity(), urlImageList, 3000,
				mMainPageGalleryLin, R.drawable.dot_focused, R.drawable.dot_normal);

				mMainPageGalleryView.setMyOnItemClickListener(new MyOnItemClickListener() {
				public void onItemClick(int curIndex) {
					App.showLog("下标=="+curIndex);
				}
			});
			
		}
		
		/** 初始化viewpage 品牌推荐  */
		private void initViewpage() {
			if( mBrandRecommends == null || mBrandRecommends.size() == 0  ){
				mMainViewpageLin.setVisibility(View.GONE);
				return;
			}
			
			mMainViewpageLin.setVisibility(View.VISIBLE);

			//防止刷新的时候点错位
			curIndex = 0;
			oldIndex = 0;

			mViewPage.setOnPageChangeListener(new OnPageChangeListener() {

				@Override
				public void onPageSelected(int position) {
					App.showLog("item_selete"+position);
					curIndex = position % viewList.size();
					App.showLog("curIndex=="+curIndex);
					App.showLog("oldIndex=="+oldIndex);
					if (mOvalLayout != null && viewList.size() > 1) { // 切换圆点

						mOvalLayout.getChildAt(oldIndex).setBackgroundResource(R.drawable.dot_normal); // 圆点取消
						mOvalLayout.getChildAt(curIndex).setBackgroundResource(R.drawable.dot_focused);// 圆点选中
						oldIndex = curIndex;
					}
				}

				@Override
				public void onPageScrolled(int paramInt1, float paramFloat, int paramInt2) {

				}
				@Override
				public void onPageScrollStateChanged(int paramInt) {
				}
			});

			viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
			LayoutInflater inflater =  getActivity().getLayoutInflater();
			for (int i = 0; i < 3; i++) {
				final int j = i;

				view = inflater.inflate(R.layout.item_main_brand_viewpage, null);
				ImageView imageView1 = (ImageView) view.findViewById(R.id.item_viewpage_image1);
				ImageView imageView2 = (ImageView) view.findViewById(R.id.item_viewpage_image2);
				ImageView imageView3 = (ImageView) view.findViewById(R.id.item_viewpage_image3);
				TextView textView1 = (TextView) view.findViewById(R.id.item_viewpage_text1);
				TextView textView2 = (TextView) view.findViewById(R.id.item_viewpage_text2);
				TextView textView3 = (TextView) view.findViewById(R.id.item_viewpage_text3);

				ImageLoader.getInstance().displayImage(mBrandRecommends.get(j*3).getAppImage(), imageView1);
				ImageLoader.getInstance().displayImage(mBrandRecommends.get(j*3+1).getAppImage(), imageView2);
				ImageLoader.getInstance().displayImage(mBrandRecommends.get(j*3+2).getAppImage(), imageView3);
				textView1.setText(mBrandRecommends.get(j*3).getName());
				textView2.setText(mBrandRecommends.get(j*3+1).getName());
				textView3.setText(mBrandRecommends.get(j*3+2).getName());

				imageView1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Log.d("TAG", "viewview-imageView1_onclick");

						Intent intent = new Intent(getActivity(),BrandListActivity.class);
						intent.putExtra("brandId", mBrandRecommends.get(j*3).getId()+"");
						intent.putExtra("brandName", mBrandRecommends.get(j*3).getName());
						startActivity(intent);

					}
				});

				imageView2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Log.d("TAG", "view-imageView2-onclick");

						Intent intent = new Intent(getActivity(),BrandListActivity.class);
						intent.putExtra("brandId", mBrandRecommends.get(j*3+1).getId()+"");
						intent.putExtra("brandName", mBrandRecommends.get(j*3+1).getName());
						startActivity(intent);
					}
				});
				imageView3.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Log.d("TAG", "view-imageView3-onclick");

						Intent intent = new Intent(getActivity(),BrandListActivity.class);
						intent.putExtra("brandId", mBrandRecommends.get(j*3+2).getId()+"");
						intent.putExtra("brandName", mBrandRecommends.get(j*3+2).getName());
						startActivity(intent);
					}
				});
				viewList.add(view);			
			}

			initOvalLayout();

			mViewPage.setAdapter(pagerAdapter);
		}

		
		
		
		  PagerAdapter pagerAdapter = new PagerAdapter() {
					@Override
					public boolean isViewFromObject(View arg0, Object arg1) {
						//根据传来的key，找到view,判断与传来的参数View arg0是不是同一个视图
	
						return arg0 == viewList.get((int)Integer.parseInt(arg1.toString()));
					}
	
					@Override
					public int getCount() {
						return viewList.size();
					}
	
					@Override
					public void destroyItem(ViewGroup container, int position,
							Object object) {
						container.removeView(viewList.get(position));
					}
					@Override
					public Object instantiateItem(ViewGroup container, int position) {
						container.addView(viewList.get(position));
						//把当前新增视图的位置（position）作为Key传过去
						return position;
					}
			};


			/** 初始化圆点 */
			private void initOvalLayout() {

				if (mOvalLayout != null && viewList.size() < 2) {// 如果只有一第图时不显示圆点容器
					mOvalLayout.removeAllViews();
					mOvalLayout.getLayoutParams().height = 0;
				} else if (mOvalLayout != null) {
					mOvalLayout.removeAllViews();
					// 圆点的大小是 圆点窗口的 70%;
					int Ovalheight = (int) (mOvalLayout.getLayoutParams().height * 0.7);
					// 圆点的左右外边距是 圆点窗口的 20%;
					int Ovalmargin = (int) (mOvalLayout.getLayoutParams().height * 0.2);
					android.widget.LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							Ovalheight, Ovalheight);
					layoutParams.setMargins(Ovalmargin, 0, Ovalmargin, 0);
					for (int i = 0; i < viewList.size(); i++) {
						View v = new View(getActivity()); // 圆点
						v.setLayoutParams(layoutParams);
						v.setBackgroundResource(R.drawable.dot_normal);
						mOvalLayout.addView(v);
					}
					// 选中第一个
					mOvalLayout.getChildAt(0).setBackgroundResource(R.drawable.dot_focused);
				}
			}
		
		
		
		
		
		
		
		
		
		


		//添加数据
		private void setTimeLimitDate() {

			if(mSpecialSales == null || mSpecialSales.isEmpty()){
				mTimeLimitLin.setVisibility(View.GONE); 
				return;
			}

			mTimeLimitImg1.setVisibility(View.VISIBLE);
			mTimeLimitImg2.setVisibility(View.VISIBLE);
			mTimeLimitImg3.setVisibility(View.VISIBLE);

			ImageView[] img = new ImageView[3];
			img[0] = mTimeLimitImg1;
			img[1] = mTimeLimitImg2;
			img[2] = mTimeLimitImg3;


			//为了应付有时候后台给的特卖不足三个
			if(img.length > mSpecialSales.size() ){
				for (int i = 0; i < mSpecialSales.size(); i++) {
					ImageLoader.getInstance().displayImage(mSpecialSales.get(i).getImage(), img[i]);
				}
			}else {
				for (int i = 0; i < img.length; i++) {
					ImageLoader.getInstance().displayImage(mSpecialSales.get(i).getImage(), img[i]);
				}
			}
			//时间差，结束时间与当前时间
			long date = msEntity.getEndDate()-msEntity.getNowDate();

			//		CustomDigitalClock remainTime = (CustomDigitalClock) findViewById(R.id.time_limit_time_text);
			CountdownClock remainTime = (CountdownClock) findViewById(R.id.time_limit_time_text);
			remainTime.setEndTime(System.currentTimeMillis()+date);
			remainTime.setClockListener(new ClockListener() {

				@Override
				public void timeEnd() {
					getSpecialSaleSync();
				}

				@Override
				public void remainFiveMinutes() {
					Log.d(TAG, "remain five minutes....");
				}
			});

		}
		
		
			@Override
			public void onStop() {
				// TODO Auto-generated method stub
				mMainPageGalleryView.stopTimer();
				super.onStop();
			}
			
			@Override
			public void onDestroy() {
				super.onDestroy();
				mHandler.removeCallbacksAndMessages(null);
			}
		
}
